package com.apes.autoparts.product.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.apes.autoparts.product.model.*;
import com.apes.autoparts.product.repository.EPCVersionContrastRepository;
import com.apes.autoparts.product.repository.OriginalProductDao;
import com.apes.autoparts.product.repository.ProductDao;
import com.apes.framework.api.DomainService;
import com.apes.framework.jpa.spec.JpaDsl;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.framework.util.MapUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * 类描述：EPC版本对照服务类
 *
 * @ClassName EPCVersionContrastService
 * @Description 描述
 * @Author wushilong
 * @Date 2022/10/9 11:19
 * @Version 1.0
 */
@Service
public class EPCVersionContrastService extends DomainService {

    @Autowired
    EPCVersionContrastRepository epcVersionContrastRepository;

    @Autowired
    private ProductDao productDao;

    @Autowired
    private OriginalProductDao originalProductDao;

    /**
     * 批量更新ERP版本对照
     *
     */
    public Map edit(SimpleRequest request){
        //新增和修改
        List<EPCVersionContrast> epcVersionContrastList = request.getA("epcVersionContrastItems", EPCVersionContrast.class);
        Set<String> epcVersionContrastSet = new HashSet<>();

        //根据id判断新增
        List<EPCVersionContrast> newEPCVersionContrast = epcVersionContrastList.stream().filter(epc -> Objects.isNull(epc.getId()) || "".equals(epc.getId()))
                .collect(Collectors.toList());

        //获取删除的数据,如果没有不删除
        if (Objects.nonNull(request.getJO().get("del"))){
            List<EPCVersionContrast> delEPCVersionContrast = request.getA("del", EPCVersionContrast.class);
            delEPCVersionContrast.forEach(epcVersionContrast -> {
                String sole =  epcVersionContrast.getAutoBrand() + epcVersionContrast.getAutoLabel() + epcVersionContrast.getEpcVersion();
                if (Objects.nonNull(epcVersionContrast.getId()) && epcVersionContrastSet.add(sole)){
                    epcVersionContrastRepository.delete(epcVersionContrast);
                }
            });
        }

        //保存并返回
        productDao.epcVersionInsert(newEPCVersionContrast);
        return MapUtil.mapper("epcVersionContrastItems", newEPCVersionContrast);

    }


    /**
     * 放弃编辑回显当前数据
     * @param request
     * @return
     */
    public Map epcVersionContrastFindOne(SimpleRequest request){
        List<EPCVersionContrast> list = request.getA("epcVersionContrastItems", EPCVersionContrast.class);
        return MapUtil.mapper("epcVersionContrastItems",list);
    }




    /**
     * 动态条件查询
     * @param request
     * @return
     */
 /*   public Map conditionQuery2(SimpleRequest request){
        JSONObject jo = request.getJO();

        String autoBrand = jo.getString("autoBrand");
        String epcVersion = jo.getString("epcVersion");
        String autoLabel = jo.getString("autoLabel");
        int page = jo.getInteger("page") < 0 ? 0 : jo.getInteger("page");
        if (Objects.isNull(autoBrand) && Objects.isNull(epcVersion) && Objects.isNull(autoLabel)) {
            Page<EPCVersionContrast> epcVersionPage = epcVersionContrastRepository.findAll(PageRequest.of(page, 50, Sort.by(Sort.Direction.DESC, "id")));
            return MapUtil.mapper("content", epcVersionPage.getContent(), "page", page, "sum", epcVersionPage.getTotalPages());
        }
        Page<EPCVersionContrast> epcVersionPage = epcVersionContrastRepository.findAll(JpaDsl.toCriteriaIgnoreNull("autoBrand", "EQ", autoBrand,
                "epcVersion", "EQ", epcVersion,
                "autoLabel", "EQ", autoLabel),
                PageRequest.of(page, 50, Sort.by(Sort.Direction.DESC, "id")));
        return MapUtil.mapper("content", epcVersionPage.getContent(), "page", page, "sum", epcVersionPage.getTotalPages());

    }*/

    /**
     * 动态条件查询
     * @param request
     */
    public Map conditionQuery(SimpleRequest request){
        JSONObject jo = request.getJO();
        JSONObject jsonObject =  (JSONObject) originalProductDao.countEPC(jo).get(0);
        Integer count = jsonObject.getInteger("COUNT");
        Integer page = jo.getInteger("page");
        Integer size = jo.getInteger("size");
        if(size>count){
            size = count;
            page = count-50;
        }
        if(page<0){
            page=0;
            size=50;
        }
        JSONArray array = originalProductDao.findAllEPCPage(jo,page,size);
        return  MapUtil.mapper("content", array, "page", page, "size",size,"sum",count);
    }





    /**
     * 定制导入ERP版本对照
     * @param request
     * @return
     */
    public JSONObject importEPCVersionContrast(SimpleRequest request){
        //Excel信息
        JSONObject importData = request.get("importData");
        JSONArray titleColumnArray = new JSONArray();
        String key = appendImportReturn_New(importData, titleColumnArray);
        JSONObject returnData = new JSONObject();
        returnData.put(key, titleColumnArray);
        return returnData;
    }

    /**
     * 并行流导入
     * @param importData
     * @param titleColumnArray
     * @return
     */
    private String appendImportReturn_New(JSONObject importData, JSONArray titleColumnArray) {

        AtomicReference<String> key = new AtomicReference<>();
        Set<String> stringHashSet = new HashSet<>();

        JSONArray titleArray = new JSONArray(3);
        titleArray.add("EPC版本号");
        titleArray.add("汽车厂牌");
        titleArray.add("汽车品牌");
        titleColumnArray.add(titleArray);

        List<EPCVersionContrast> dataList = Collections.synchronizedList(new ArrayList());
        importData.forEach((k, v) -> {
            key.set(k);
            JSONArray importDataValueArray = (JSONArray) v;
            importDataValueArray.parallelStream().forEach( item -> {
                JSONArray iValueArray = (JSONArray) item;
                if (iValueArray.size() == 0) return;
                String epcVersion = "";
                String autoLabel = "";
                String autoBrand = "";
                EPCVersionContrast epcVersionContrast = new EPCVersionContrast();
                for (int i = 0; i < iValueArray.size(); i++) {
                    if (Objects.isNull(iValueArray.get(i))) continue;
                    switch (i) {
                        case 0:
                            epcVersion = iValueArray.getString(0);
                            break;
                        case 1:
                            autoLabel = iValueArray.getString(1);
                            break;
                        case 2:
                            autoBrand = iValueArray.getString(2);
                            break;
                    }
                }

                if ("EPC版本号".equals(epcVersion) && "汽车品牌".equals(autoBrand)) return;  // 匹配中英文

                if (!stringHashSet.add(autoLabel)) throw new RuntimeException("导入重复数据，请重新导入！");

                epcVersionContrast.setEpcVersion(epcVersion);
                epcVersionContrast.setAutoLabel(autoLabel);
                epcVersionContrast.setAutoBrand(autoBrand);

                dataList.add(epcVersionContrast);
            });
        });

        productDao.epcVersionInsert(dataList);
        return key.get();
    }


    /**
     * 下载
     * @param request
     * @return
     */
    public Map download(SimpleRequest request) {
        JSONArray array = originalProductDao.findAll(request.getJO());
        return MapUtil.mapper("content", array, "total", array.size(), "pages", 50, "page", 1);
    }



    /**
     * 批量删除
     *
     * @param request
     * @return
     */
    public Map delEPCVersionContrast(SimpleRequest request){
        List<EPCVersionContrast> epcVersionContrasts = request.getA("del", EPCVersionContrast.class);
        for (EPCVersionContrast epcVersionContrast : epcVersionContrasts) {
            epcVersionContrastRepository.delete(epcVersionContrast);
        }
        request.setBody(request.getJO().getString("model"));
        return conditionQuery(request);
    }


    /**
     * 添加
     * @param request
     * @return
     */
    public EPCVersionContrast insertEPCVersionContrast(SimpleRequest request){
        JSONObject jo = request.getJO();
        EPCVersionContrast epcVersionContrast  = jo.getObject("data",EPCVersionContrast.class);

        try{
            epcVersionContrast =   epcVersionContrastRepository.saveAndFlush(epcVersionContrast);
            return epcVersionContrast;
        }catch (Exception e) {
            throw new RuntimeException("添加失败，汽车品牌不能重复！");
        }
    }


}
